# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 00:35:11 2013

@author: Winand
"""

import subprocess, settings, socket
from webapi import config

def __dispIpAddr(addr): #binary ip to string
    try: return socket.inet_ntoa(addr)
    except socket.error: return None

#get broadcast address on specified iface using 'ip' system utility
def __getBroadcastAddr(iface):
    try:
        p=subprocess.Popen(["ip", "-o", "-4", "addr", "show", iface], stdout=subprocess.PIPE)
        data = p.communicate()
    except: return "" #no ip util
    dat_chunks = data[0].split()
    ip, brd = None, None
    for i,v in enumerate(dat_chunks):
        if i==len(dat_chunks)-1: break
        if v=="brd": return dat_chunks[i+1]
        
def getBroadcastAddress(): #try every available way to get broadcast addr
    #settings->system->hard-coded
    return __dispIpAddr(config.cget("wake/broadcast", "")) or \
        __getBroadcastAddr(settings.S_WAKE_IFACE) or \
        getattr(settings, "S_WAKE_BROAD", "")
        
def parseDispMacAddr(addr):
    if len(addr) == 12: sep = None
    elif len(addr) == 17: sep = addr[2]
    else: return
    addr = "".join(addr.split(sep))
    try:
        return "".join(["%c" % int(addr[i:i+2], 16) for i in range(0, 12, 2)])
    except ValueError: return #wrong string
    